package com.iuhao.orange.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 请求日志切点类
 * 
 * @author viruser
 */
@Aspect
@Component
public class RequestLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(RequestLogAspect.class);

    // Controller层切点
    @Pointcut("execution( * com.springboot.controller.*.*(..))")
    public void controllerRequestAspect() {

    }

    // Controller层切点
    @Pointcut("execution( * com.springboot.controller.*.*(..))")
    public void controllerRequestAllAspect() {

    }

    /**
     * 用于拦截Controller层
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("controllerRequestAspect()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            String methodName = joinPoint.getSignature().getName();
            String className = joinPoint.getTarget().getClass().getName();
            Object[] args = joinPoint.getArgs();
            String logStr = className + "." + methodName + ": ";
            for (int i = 0; i < args.length; i++) {
                logStr += (i == 0 ? "" : ",") + (args[i] == null ? "NULL" : args[i].toString() + "\n");
            }
            logger.info("获取到请求======>" + logStr);
        } catch (Exception e) {
            // 记录本地异常日志
            logger.error("==请求日志输出异常==" + e.getMessage());
        }
    }

    /**
     * 用于拦截Controller层
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Around("controllerRequestAllAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String prefix = "";
        Object result = null;
        try {
            String methodName = joinPoint.getSignature().getName();
            String className = joinPoint.getTarget().getClass().getName();
            Object[] args = joinPoint.getArgs();
            String logStr = className + "." + methodName + ": ";
            prefix = logStr;
            for (int i = 0; i < args.length; i++) {
                logStr += (i == 0 ? "" : ",") + (args[i] == null ? "NULL" : args[i].toString());
            }
            logger.info("获取到请求======>" + logStr);
            result = joinPoint.proceed();
            logger.info("获取到应答======>" + prefix + (result == null ? "NULL" : result.toString()) + "\n");
        } catch (Exception e) {
            // 记录本地异常日志
            logger.error("==请求应答日志输出异常==" + e.getMessage());
        }
        return result;
    }

}
